package com.plugin.manage.security;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * 自定义权限评估器，用于判断用户是否拥有特定权限
 * 特别处理admin用户，赋予其最大权限
 *
 * @author mark
 * @date 2025-08-03
 */
@Component
public class AdminPermissionEvaluator implements PermissionEvaluator {

    private static final String ROLE_ADMIN = "ROLE_ADMIN";

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        if (authentication == null || targetDomainObject == null || !(permission instanceof String)) {
            return false;
        }

        // 检查是否是admin角色，如果是则拥有所有权限
        if (isAdmin(authentication)) {
            return true;
        }

        // 针对非admin用户的常规权限检查逻辑
        String targetType = targetDomainObject.getClass().getSimpleName().toLowerCase();
        return hasPrivilege(authentication, targetType, permission.toString().toLowerCase());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        if (authentication == null || targetType == null || !(permission instanceof String)) {
            return false;
        }

        // 检查是否是admin角色，如果是则拥有所有权限
        if (isAdmin(authentication)) {
            return true;
        }

        // 针对非admin用户的常规权限检查逻辑
        return hasPrivilege(authentication, targetType.toLowerCase(), permission.toString().toLowerCase());
    }

    /**
     * 检查用户是否拥有特定权限
     */
    private boolean hasPrivilege(Authentication authentication, String targetType, String permission) {
        for (GrantedAuthority authority : authentication.getAuthorities()) {
            // 格式: targetType_permission，例如: elder_read, elder_write
            if (authority.getAuthority().equalsIgnoreCase(targetType + "_" + permission)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断当前用户是否为admin角色
     */
    private boolean isAdmin(Authentication authentication) {
        return authentication.getAuthorities().stream()
                .anyMatch(authority -> ROLE_ADMIN.equals(authority.getAuthority()));
    }
}
